/*
 * Tencent is pleased to support the open source community by making Tinker available.
 *
 * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved.
 *
 * Licensed under the BSD 3-Clause License (the "License"); you may not use instance file except in
 * compliance with the License. You may obtain a copy of the License at
 *
 * https://opensource.org/licenses/BSD-3-Clause
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License is
 * distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
 * either express or implied. See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.example.administrator.szb.tinkerutil;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.support.multidex.MultiDex;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;
import com.example.administrator.szb.R;
import com.example.administrator.szb.activity.HomeActivity;
import com.example.administrator.szb.activity.LoginNewActivity;
import com.example.administrator.szb.activity.WecomeActivity;
import com.example.administrator.szb.bean.IndexBean;
import com.example.administrator.szb.bean.JClientBean;
import com.example.administrator.szb.bean.Login;
import com.example.administrator.szb.bean.UserBase;
import com.example.administrator.szb.callbackconfig.XFCCallBack;
import com.example.administrator.szb.util.DialogUtil;
import com.example.administrator.szb.util.FinishActivity;
import com.example.administrator.szb.util.QTLog;
import com.example.administrator.szb.util.SPUtils;
import com.example.administrator.szb.util.SharedPreferencesUtil;
import com.qiniu.android.common.FixedZone;
import com.qiniu.android.storage.Configuration;
import com.qiniu.android.storage.UploadManager;
import com.umeng.socialize.PlatformConfig;
import com.umeng.socialize.UMShareAPI;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;

import cn.jpush.android.api.JPushInterface;
import cn.jpush.im.android.api.JMessageClient;
import cn.jpush.im.android.api.event.LoginStateChangeEvent;
import cn.jpush.im.android.api.model.UserInfo;


public class SampleApplicationLike extends Application {


    public static int FLAGS = -1;
    private static RequestQueue queue;
    private static Login.DataBean user_login_data;
    private static IndexBean indexBean=null;
    private static ArrayList<Activity> activities;
    private static Configuration config;
    private static UploadManager uploadManager;
    private static String key = "user_instance";//保存用户登录信息
    private static String key_color = "yw_color";
    private static Application instance;
    public  static boolean isDebugs = false;
    Handler handler = new Handler(){
        @Override
        public void handleMessage(android.os.Message msg) {
            QTLog.e("极光退出登录");
            JClientBean jClientBean = new JClientBean();
            if (msg.what==1){
                jClientBean.setMsg("您的市值宝账号密码在其他设备上被修改");
            }else {
                jClientBean.setMsg("您的市值宝账号在其他设备上登录，如非本人操作，请立即修改密码");
            }
            EventBus.getDefault().post(jClientBean);
            /*//Toasts.show(instance, "Mytest", Toast.LENGTH_SHORT);
            JMessageClient.logout();//极光退出登录
           // HomeActivity.isClick = 2;
            SharedPreferencesUtil.savaData(instance, new Login.DataBean(), SampleApplicationLike.getKey());
            SampleApplicationLike.setUserloginInstance(new Login.DataBean());
            showXFC();*/
        }
    };

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);
    }

    public static Application getInstance() {
        return instance;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        instance = this;
        if (!isDebugs){
            Thread.setDefaultUncaughtExceptionHandler(restartHandler); // 程序崩溃时触发线程  以下用来捕获程序崩溃异常
        }

        initData();//初始化一些数据
    }
    // 创建服务用于捕获崩溃异常
    private Thread.UncaughtExceptionHandler restartHandler = new Thread.UncaughtExceptionHandler() {
        public void uncaughtException(Thread thread, Throwable ex) {

            if (isDebugs){
                return;
            }
            restartApp();//发生崩溃异常时,重启应用
        }
    };
    //重启App
    public void restartApp(){
        FinishActivity.finish();
        Intent intent = new Intent(instance,WecomeActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        instance.startActivity(intent);
        android.os.Process.killProcess(android.os.Process.myPid());  //结束进程之前可以把你程序的注销或者退出代码放在这段代码之前
    }
    private void initData() {
        //极光推送
        JPushInterface.setDebugMode(isDebugs); 	// 设置开启日志,发布时请关闭日志
        JPushInterface.init(instance);
        //极光IM
        JMessageClient.init(instance);


        JMessageClient.registerEventReceiver(this);

        //JPushInterface.setAlias(instance,0,getUserloginInstance().getId()+"");
        //  Config.DEBUG = true;
        UMShareAPI.get(instance);//友盟分享



//        try{
//            WbSdk.install(instance,new AuthInfo(instance, Constants.APP_KEY, Constants.REDIRECT_URL, Constants.SCOPE));
//        }catch (Exception e){
//            e.toString();
//        }




        queue = Volley.newRequestQueue(instance);
        user_login_data = new Login.DataBean();
        activities = new ArrayList<Activity>();
        config = new Configuration.Builder()
                // keyGen 分片上传时，生成标识符，用于片记录器区分是那个文件的上传记录
                .zone(FixedZone.zone0)        // 设置区域，指定不同区域的上传域名、备用域名、备用IP。
                .build();
// 重用uploadManager。一般地，只需要创建一个uploadManager对象
        uploadManager = new UploadManager(config);
    }

    {
        PlatformConfig.setWeixin("wx49d78b6e676100ea", "36f429e955cd8cae8865ee05fcd0cb54");
        PlatformConfig.setQQZone("1106491664", "1g0fD0H6jj63inIF");
        PlatformConfig.setSinaWeibo("803720758", "4b647d4168921a24a8968cc1e948f914","http://sns.whalecloud.com");
    }



    public static void showXFC() {
        DialogUtil.showAllPopuwindow(R.layout.view_xfc, new XFCCallBack() {
            @Override
            public void initView(final View view_, final Context context) {
                ((TextView)view_.findViewById(R.id.textView14_xfc)).setText("异地登录");
                ((TextView)view_.findViewById(R.id.textView8_xfc)).setText("您的市值宝账号在其他设备上登录，如非本人操作，请立即修改密码");
                ((TextView)view_.findViewById(R.id.textView9_xfc)).setText("返回首页");
                ((TextView)view_.findViewById(R.id.textView15_xfc)).setText("立即登录");


                ((TextView)view_.findViewById(R.id.textView9_xfc)).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Intent intent = new Intent(context, HomeActivity.class);
                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        context.startActivity(intent);
                        DialogUtil.mWindowManager.removeView(view_);
                    }
                });

                ((TextView)view_.findViewById(R.id.textView15_xfc)).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Intent intent = new Intent(context, LoginNewActivity.class);
                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        context.startActivity(intent);
                        DialogUtil.mWindowManager.removeView(view_);
                    }
                });

            }
        });
    }


    public void onEventMainThread(LoginStateChangeEvent event){
        LoginStateChangeEvent.Reason reason = event.getReason();//获取变更的原因
        UserInfo myInfo = event.getMyInfo();//获取当前被登出账号的信息
        switch (reason) {
            case user_password_change:
                //用户密码在服务器端被修改
                Log.e("pdf", "onEvent:  pass change" );
                //JPushUtils.updateUserPassword(event.);
                handler.sendEmptyMessage(1);
                break;
            case user_logout:
                Log.e("pdf", "onEvent:  lgin_out" );
                handler.sendEmptyMessage(0);

                break;
            case user_deleted:
                //用户被删除
                Log.e("pdf", "onEvent: user del" );
                break;
        }
    }


    /**
     * 获取网络队列实例
     * @return
     */
    public static RequestQueue getQueueInstance(){
        return queue;
    }

    /**
     * 获取用户实例
     * @return
     */
    public static Login.DataBean getUserloginInstance(){
        Login.DataBean bean = new Login.DataBean();
        UserBase userBase = SPUtils.getUserinfo();
        if (userBase==null){
            Login.DataBean.InfoBean infoBean = new Login.DataBean.InfoBean();
            infoBean.setName("0");
            bean.setId(0);
            bean.setInfo(infoBean);
        }else {
            bean.setId(userBase.getId());
            bean.setJpushpass(userBase.getJpushpass());
            bean.setType(userBase.getType());
            bean.setStatus(userBase.getStatus());
            Login.DataBean.InfoBean infoBean = new Login.DataBean.InfoBean();
            infoBean.setName("0");
            if (userBase.getInfo()!=null&&userBase.getInfo().getName()!=null){
                infoBean.setName(userBase.getInfo().getName());
            }


            bean.setInfo(infoBean);
        }
        setUserloginInstance(bean);
        return user_login_data;
    }

    public static void setUserloginInstance(Login.DataBean user_login){
        user_login_data = user_login;
    }

    public static UploadManager getUpLoadManager(){
        return uploadManager;
    }


    /**
     * 获取首页的实例
     * @return
     */
    public static IndexBean getIndexBeanInstance(){
        if (indexBean!=null){
            return indexBean;
        }
        return (IndexBean) SharedPreferencesUtil.getData(instance,"index");
    }
    public static void setIndexBeanInstance(IndexBean indexBean_new){
        indexBean = indexBean_new;
    }

    /**
     * 获取activities集合
     */
    public static ArrayList<Activity> getActivitiesInstance(){
        return activities;
    }

    /**
     * 退出所有的activity
     */
    public  static void  exitActivities(){
        for (Activity activity: activities) {
            if(activity != null){
                activity.finish();
            }
        }
    }

    public static String getKey() {
        return key;
    }
}
